import { _decorator, Component, UIOpacity, Tween, tween } from "cc";
import { eventDispatcher } from "../Constants";
import { EventType } from "../enums/EventType";
const { ccclass } = _decorator;

@ccclass("FadeTransition")
export class FadeTransition extends Component {

    private _uiOpacity: UIOpacity = null;
    private _tween: Tween<UIOpacity> = null;

    public onLoad(): void {
        this._uiOpacity = this.getComponent(UIOpacity);
    }

    public onEnable(): void {
        eventDispatcher.on(EventType.LOAD_SCENE_START, this.onLoadSceneStart, this);
        eventDispatcher.on(EventType.LOAD_SCENE_FINISH, this.onLoadSceneFinish, this);
    }

    public onDisable(): void {
        eventDispatcher.targetOff(this);
        this.killTween();
    }

    private onLoadSceneStart(duration: number = 0.2): void {
        this.killTween();
        this._tween = tween(this._uiOpacity)
            .to(duration, { opacity: 255 })
            .start();
    }

    private onLoadSceneFinish(duration: number = 0.8): void {
        this.killTween();
        this._tween = tween(this._uiOpacity)
            .set({ opacity: 255 })
            .to(duration, { opacity: 0 })
            .start();
    }

    private killTween(): void {
        if (this._tween) {
            this._tween.stop();
            this._tween = null;
        }
    }
}